package sp.util.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailUtils {

    public static void sendMail(String emailTo, String emailMsg)
            throws AddressException, MessagingException {

        // 1.创建一个程序与邮件服务器会话对象 Session
        Properties props = System.getProperties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", "smtp.qq.com"); //发邮件的服务器地址
        props.setProperty("mail.smtp.auth", "true");//需要验证，不验证会提示没有权限发送
        //QQ邮箱需要下面这段代码，163邮箱不需要
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");


        try {
          
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                	// 发件人邮箱账号、授权码
                    return new PasswordAuthentication("lkg18634185909@qq.com", "cqpclmpaffmmbaie"); 
                }
            });
            
            

            // 2.创建一个Message，它相当于是邮件内容
            Message message = new MimeMessage(session);
            
            message.setFrom(new InternetAddress("lkg18634185909@qq.com")); // 设置发送者

            message.setRecipient(RecipientType.TO, new InternetAddress(emailTo)); // 设置发送方式与接收者

            message.setSubject("账号激活");
            // message.setText("这是一封激活邮件，请<a href='#'>点击</a>");

            message.setContent(emailMsg, "text/html;charset=utf-8");

            // 3.创建 Transport用于将邮件发送
            Transport.send(message);
        } catch (Exception e) {
			e.printStackTrace();
		}

    }
}








































